from flask import Blueprint,request,jsonify
import json
from db import db1
from utils.jwtc import myjwt
from utils.acl import acl
from utils.redisc import red
bp_user = Blueprint('user',__name__)

@bp_user.route('/login',methods=['POST'])
def login():
    data = request.data
    if data:
        data = json.loads(data)
    else:
        data = request.form
    sql = "select * from user where username='%s' and password='%s'"%(data['username'],data['password'])
    res = db1.find(sql)
    data = {'id':res['id'],'username':res['username']}
    token = myjwt.jwt_encode(data)
    pagelist = acl.get_interface_reslist(res['id'])
    interfacelist = acl.get_interface_reslist(res['id'])
    key = 'interface'+str(res['id'])
    red.insert_set(key,interfacelist)
    if res:
        return jsonify({'code':200,'userid':res['id'],'username':res['username'],'token':token,'pagelist':pagelist})
    else:
        return jsonify({'code':20010,'mes':'用户名或密码错误'})


def free(data):
    list = []
    idlist=[]
    for i in data:
        id = i['id']
        if id not in idlist:
            list.append({'id':id,'name':i['pname'],'son':[]})
            idlist.append(id)
    for j,value in enumerate(list):
        for i in data:
            if value['id']==i['pid']:
                list[j]['son'].append({'id':i['id'],'name':i['name'],'url':i['url']})
        return list


@bp_user.route('/getrole')
def getrole():
    userid = request.args.get('userid')
    sql = "select role.name,role.url from user_role left join role on user_role.role_id=role.id where user_id=%d and role.type=2"%(int(userid))
    res = db1.findall(sql)
    return  jsonify({'code':200,'list':res})

@bp_user.route('/test1')
def test1():
    key = 'abac'
    red.insert_hash(key,'ip','127.0.0.1')
    red.insert_hash(key,'level','003')
    red.insert_hash(key,'time',"['2021-10-10','2021-12-10']")
    value = red.get_all_hash(key)
    print(value)
    return 'ok'

@bp_user.route('/roleM',methods=['POST,GET,DELETE,PUT'])
def roleM():
    pass

@bp_user.route('/getpost')
def getpost():
    sql = "select * from post"
    res = db1.findall(sql)
    return jsonify({'code':200,'list':res})

